package com.ruoyi.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.domain.BasisEvent;
import com.ruoyi.mapper.BasisEventMapper;
import com.ruoyi.service.BasisEventService;
import com.ruoyi.service.BasisLabelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yichaofan
 * date 2025/5/27
 */
@Service
public class BasisEventServiceImpl implements BasisEventService {
    @Autowired
    BasisEventMapper eventMapper;
    @Autowired
    BasisLabelService labelService;
    @Override
    public List<BasisEvent> selectEventByLoadingId(String loadingId) {
        List<BasisEvent> basisEvents = eventMapper.selectEventByLoadingId(loadingId);
        List<BasisEvent> all =new ArrayList<>();
        for (BasisEvent basisEvent : basisEvents) {
//            basisEvent.setChildren(labelService.seletLableByEventId(basisEvent.getId()));
            if(basisEvent.getParentId()==0){
                setChildEventFromEvent(basisEvent,basisEvents);
                all.add(basisEvent);
            }
        }
        return all;
    }

    public void setChildEventFromEvent(BasisEvent basisEvent,List<BasisEvent> basisEvents){

        List<BasisEvent> events = basisEvents.stream()
                .filter(event -> event.getParentId() != 0 && event.getParentId().equals(basisEvent.getId()))
                .collect(Collectors.toList());
        basisEvent.setChildren(events);
        events.forEach(event -> {
            setChildEventFromEvent(event,basisEvents);
        });

    }

    @Override
    public void insertEvent(BasisEvent event) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        event.setUserId(user.getUserId());
        event.setCreateTime(new Date());
        if(event.getParentId()==0){
            event.setAncestors("0");
        }else{
            BasisEvent info = eventMapper.selectEventById(event.getParentId());
            event.setAncestors(info.getAncestors() + "," + event.getParentId());
        }
        eventMapper.insertEvent(event);
    }

    @Override
    public void deleteEvent(Long[] ids) {
        eventMapper.deleteEvent(ids);
    }

    @Override
    public void updateEvent(BasisEvent event) {
        eventMapper.updateEvent(event);
    }

    @Override
    public BasisEvent selectEventById(Long eventId) {
        return eventMapper.selectEventById(eventId);
    }
}
